package com.zeratul.common.i18n.config;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.zeratul.common.i18n.config.prop.I18nProperties;
import com.zeratul.common.i18n.source.nacos.base.NacosResourceMessageSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;

@AutoConfiguration(before = I18nLocalMessageSourceConfiguration.class)
@RefreshScope
@ConditionalOnClass(name = "com.alibaba.cloud.nacos.NacosConfigManager")
@ConditionalOnProperty(prefix = "i18n.config", name = "enabled", havingValue = "true", matchIfMissing = true)
@Slf4j
public class I18nNacosMessageSourceConfiguration {

    @Autowired
    private I18nProperties i18NProperties;

    @Autowired
    private NacosConfigManager nacosConfigManager;

    /**
     * 微服务名称
     */
    @Value("${spring.application.name}")
    private String groupName;

    /**
     * 基于Nacos的国际化消息来源
     * @return
     */
    @SuppressWarnings("ContextJavaBeanUnresolvedMethodsInspection")
    @RefreshScope
    @Bean(initMethod = "init")
    @ConditionalOnProperty(prefix = "i18n.config", name = "mode", havingValue = "nacos", matchIfMissing = true)
    public MessageSource messageSource() {
        I18nProperties.Nacos nacosConfig = i18NProperties.getNacos();
        if (ObjectUtil.isEmpty(nacosConfig.getGroupName())) {
            nacosConfig.setGroupName(groupName);
        }
        log.debug("【国际化】基于Nacos的语言配置模式加载：{}", nacosConfig);
        //根据文件格式获取对应的国际化数据源，默认json格式
        NacosResourceMessageSource messageSource = NacosResourceMessageSource.getInstance(nacosConfig.getFormat().getName());
        //配置Nacos中的配置文件名称（也就是dataId），默认message
        messageSource.addBasenames(nacosConfig.getBaseDataId());
        //配置基础报名，默认base  该包的国际化配置，一定会被加载
        messageSource.setBaseGroupName(nacosConfig.getBaseGroupName());
        //设置读取的组名称，可以添加多个组名，先添加的组名读取到的配置的优先级越高（同名的配置，优先级高的会覆盖优先级低的配置）
        //默认为当前服务名称
        messageSource.addGroupName(nacosConfig.getGroupName());
        //设置编码
        messageSource.setDefaultEncoding(nacosConfig.getEncoding());
        //设置nacos管理器
        messageSource.setNacosConfigManager(nacosConfigManager);
        return messageSource;
    }
}
